package com.sensePlusVR.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensePlusVR.adapter.GameListAdapter;
import com.sensePlusVR.adapter.HotTrailerPagerAdapter;
import com.sensePlusVR.base.BaseFragment;
import com.sensePlusVR.bean.BannersDto;
import com.sensePlusVR.bean.EventBusBean;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.BannerManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.manager.GameItemManager;
import com.sensePlusVR.receiver.HomeListener;
import com.sensePlusVR.receiver.ScreenObserver;
import com.sensePlusVR.utils.BitmapUtil;
import com.sensePlusVR.utils.CommonType;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.DialogUtils;
import com.sensePlusVR.utils.EventBusUtils;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.NetworkUtils;
import com.sensePlusVR.utils.PageUtil;
import com.sensePlusVR.widget.FullyLinearLayoutManager;
import com.sensePlusVR.widget.refresh.OnLoadMoreListener;
import com.sensePlusVR.widget.refresh.OnRefreshListener;
import com.sensePlusVR.widget.refresh.SwipeToLoadLayout;
import com.senseplusvr.sdk.videoview.GLView;
import com.senseplusvr.sdk.videoview.SvrVideoView;
import com.senseplusvr.sdk.videoview.SvrVideoView.OnSvrEventListener;
import com.senseplusvr.sdk.videoview.SvrVideoView.playerEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author: Loren
 * @create: 2016-8-10下午3:04:45
 * @desc:Home --> 视频界面 
 *
 */
@SuppressLint({ "ClickableViewAccessibility", "HandlerLeak" }) @SuppressWarnings({ "unused"})
@ContentView(R.layout.fragment_game)
public class GameFragment extends BaseFragment  implements
OnRefreshListener, OnLoadMoreListener,OnClickListener{
	private static final String TAG = GameFragment.class.getSimpleName();
	private List<GameItem> gameList = new ArrayList<GameItem>();
	//private Map<Integer, GameItem> gameMap;
	private GameListAdapter adapter;
	private DataCenter dataCenter;
	@ViewInject(R.id.swipe_target)
	private RecyclerView game_listview;
	
	@ViewInject(R.id.swipeToLoadLayout)
	private SwipeToLoadLayout swipeToLoadLayout;
	
	private int pageSize = PageUtil.GAME_PAGE_SIZE;
	
	private boolean isUpdated = false;//主要是为了添加更新大于1页的情况
	private String KEY=this.getClass().getSimpleName();
	
	private boolean isFirstRefreshData = true;
	private boolean isShowHeader = true;
	
	
	private ScreenObserver mScreenObserver;
	private HomeListener mHomeListen;
	
	private boolean isHomeIn = false;
	private boolean isScreenOn = false;
	
	
	private ImageView[] imageViews = null;
	private ImageView imageView = null;
	private View banner_rootView = null;
	private ViewPager advPager = null;
	private RelativeLayout banner_cover_ui_relative = null;
	private TextView banner_title_tv = null;
	private ImageView banner_play_iv =null;
	private TextView banner_remark_tv = null;
	private ViewGroup group = null;
	private AtomicInteger atomicInteger = new AtomicInteger(0);
	private boolean isContinue = true;
	private boolean isWhileLoop = true;
	private MyThread myThread;
	
	private List<View> svrVideoViewList;
	private int cursvrVideoViewPosition = 0;
	
	private static final int MSG_WHAT_BANNER_POINT = 10;
	private static final int MSG_WHAT_INIT_PAGER = 11;
	
	private static final int MSG_DELAY_BANNER_POINT = 2000;
	private static final int MSG_DELAY_INIT_PAGER = 300;
	
	
	private Handler viewHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MSG_WHAT_BANNER_POINT) {
				advPager.setCurrentItem(msg.arg1);
			}else if(msg.what == MSG_WHAT_INIT_PAGER){
				List<BannersDto> bannersDtos = (List<BannersDto>) msg.obj;
				initViewPager(bannersDtos);
			}
			super.handleMessage(msg);
		}

	};
	
	EventListener gameListener = new EventListener(){

		@SuppressWarnings("unchecked")
		@Override
		public void Notify(int event, Object data, Object Params) {
			MyLog.d(TAG, "gameListener event = "+event);
			if (Params == null || data == null)
				return;
			if (event == GameItemManager.EventGameItemAllGot ||
					event == GameItemManager.EventGameItemMoreGot || event == GameItemManager.EventGameItemRefreshGot) {
				List<GameItem> giList = (List<GameItem>)data;
				boolean isRefresh = false;
				if(event == GameItemManager.EventGameItemRefreshGot){
					isRefresh = true;
				}
				if(giList == null)return;
				MyLog.e(TAG, "add to adapter to list size="+giList.size()+" isRefresh="+isRefresh);
				if(giList.size() > 0){
					if(gameList == null)gameList = new ArrayList<GameItem>();
					if (adapter != null){
						MyLog.d(TAG, "adapter != null");
						adapter.addList(giList,isRefresh);
						if(event == GameItemManager.EventGameItemRefreshGot){
							if(adapter.isHaveHeader()){
								game_listview.scrollToPosition(1);	
							}else{
								game_listview.scrollToPosition(0);
							}
						}
					}else{
						gameList.addAll(giList);
					}
				}
			}
		}
	};
	
	
	EventListener bannerListener = new EventListener(){
	
		@SuppressWarnings("unchecked")
		@Override
		public void Notify(int event, Object data, Object Params) {
			MyLog.d(TAG, "bannerListener event = " + event);
			if (Params == null || data == null)
				return;
			if(event == BannerManager.EventBannerList){
				List<BannersDto> bannersDtos = (List<BannersDto>)data;
				MyLog.d(TAG, "bannersDtos size : " + bannersDtos.size());
				if(bannersDtos != null){
					if(bannersDtos.size() > 0){
						Message msg = viewHandler.obtainMessage();
						msg.what = MSG_WHAT_INIT_PAGER;
						msg.obj = bannersDtos;
						viewHandler.sendMessageDelayed(msg, MSG_DELAY_INIT_PAGER);
					}else{
						if(adapter != null)
						adapter.setHeaderView(null);
					}
				}
			}

		}
	};
	
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//gameMap = new HashMap<Integer, GameItem>();
		dataCenter = DataCenter.getInstans();
		dataCenter.resetGameDb();
		
		initHomeListen();
		
		initScreenOnListen();
		
	}
	
	/**
	 * Home键监听
	 */
	private void initHomeListen() {
	    mHomeListen = new HomeListener(getActivity());
	    mHomeListen.setOnHomeBtnPressListener(new HomeListener.OnHomeBtnPressLitener() {
	        @Override
	        public void onHomeBtnPress() {
	            isHomeIn = true;
	            MyLog.d(TAG,"OnHomeBtnPressLitener isHomeIn ： " + isHomeIn);
	        }

	        @Override
	        public void onHomeBtnLongPress() {}
	    });
	    
	    if(isHomeIn){
			isHomeIn = false;
		}
		if(mHomeListen != null)mHomeListen.start();
	}
	
	/**
	 * 电源键监听
	 */
	private void initScreenOnListen(){
		mScreenObserver = new ScreenObserver(getActivity());
	    mScreenObserver.requestScreenStateUpdate(new ScreenObserver.ScreenStateListener() {
	          @Override
	          public void onScreenStateChange(boolean isScreenOn) {
	        	  GameFragment.this.isScreenOn = isScreenOn;
	           Log.d(TAG, "onScreenStateChange isScreenOn : " + isScreenOn);
	          }
	      });
	    
	    if(isScreenOn){
	    	isScreenOn = false;
	    }
	}
	
	
		
	private void updateGameList(List<GameItem> giList) {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		MyLog.d(TAG, "setUserVisibleHint : " + isVisibleToUser);
		if(!isVisibleToUser){
			stopVideoPlay();
			isContinue = false;
		}else{
			isContinue = true;
		}
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		MyLog.d(TAG, "onCreateView...");
		View view = x.view().inject(this, inflater, container);
		
		beforeView();
		initView();
		
		return view;
	}
	
	private void beforeView() {
		isShowHeader = true;
		atomicInteger.getAndSet(0);
		if (gameList == null){
			gameList = new ArrayList<GameItem>();
		}
		dataCenter.addGameEventListener(gameListener, this, KEY);
		dataCenter.addBannerEventListener(bannerListener,this, KEY);
		if (gameList.size() == 0){
			getGameListMore();
		}
		MyLog.d(TAG, "isFirstRefreshData : " + isFirstRefreshData);
		if(isFirstRefreshData){
			getGameListRefresh(true);
			isFirstRefreshData = false;
		}else{
			getGameListRefresh();
		}
		
		MyLog.d(TAG, "list size="+gameList.size());
		adapter = new GameListAdapter(getActivity(),gameList);
	}

	private void getBannerList(boolean update) {
		MyLog.d(TAG, "getBannerList update : " + update);
		List<BannersDto> bannersDtos = dataCenter.getBannerList(CommonType.GAME.getValue(),update);
		if(bannersDtos != null){
			if(bannersDtos.size() > 0){
				MyLog.d(TAG, "getBannerList size : " + bannersDtos.size());
				Message msg = viewHandler.obtainMessage();
				msg.what = MSG_WHAT_INIT_PAGER;
				msg.obj = bannersDtos;
				viewHandler.sendMessageDelayed(msg, 0);
			}else{
				if(adapter != null)
					adapter.setHeaderView(null);
			}
		}
	}
	
	private void initView() {
		swipeToLoadLayout.setOnRefreshListener(this);
		swipeToLoadLayout.setOnLoadMoreListener(this);
		
		FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(getActivity());
		game_listview.setLayoutManager(layoutManager);
		game_listview.setAdapter(adapter);
		
	}
	
	@SuppressWarnings("deprecation")
	private void initViewPager(List<BannersDto> bannersDtos){
		MyLog.d(TAG, "initViewPager banner size : " + bannersDtos.size());
		if(isShowHeader){
			banner_rootView = LayoutInflater.from(getActivity()).inflate(R.layout.hot_header_item, game_listview, false);
			advPager = (ViewPager) banner_rootView.findViewById(R.id.adv_pager);
			banner_cover_ui_relative = (RelativeLayout) banner_rootView.findViewById(R.id.banner_cover_ui_relative);
			banner_title_tv = (TextView) banner_rootView.findViewById(R.id.banner_title_tv);
			banner_play_iv = (ImageView) banner_rootView.findViewById(R.id.banner_play_iv);
			banner_remark_tv = (TextView) banner_rootView.findViewById(R.id.banner_remark_tv);
			group = (ViewGroup) banner_rootView.findViewById(R.id.viewGroup);
			banner_play_iv.setOnClickListener(this);
			
			isShowHeader = false;
			
		}
		
		group.removeAllViews();
		
		svrVideoViewList = new ArrayList<View>();
		imageViews = new ImageView[bannersDtos.size()];
		
		for(int i = 0;i < bannersDtos.size();i++){
			//设置Banner图片
			BannersDto bannerDto = bannersDtos.get(i);
			String imageUrl = bannerDto.getCoverUrl();
			final String title = bannerDto.getTitle();
			final String videoUrl = bannerDto.getTargetParam();
			
			//从初始化SvrVideoView到设置图片一个Item平均耗时200ms,其中初始化平均消耗50ms,设置默认图片消耗大改150ms（优化BitmapFactory.decodeResource异步）
			final SvrVideoView svrVideoView = new SvrVideoView(getActivity());
			svrVideoView.setLayoutParams(new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT));
			
			svrVideoViewList.add(svrVideoView);
			
			Bitmap bitmap = BitmapUtil.getBitmapFromResID(getActivity(), R.drawable.loadng_img);
			svrVideoView.setVideoPara(title,videoUrl, GLView.VideoType.video_2d, bitmap);
			
			ImageLibrary.getInstance().getImageBitmap(getActivity(), imageUrl, new Callback() {
				@Override
				public void onImageDownloaded(final Bitmap bitmap) {
					if (bitmap != null){
						svrVideoView.setVideoPara(title,videoUrl, GLView.VideoType.video_2d, bitmap);
					}
				}
			});
			svrVideoView.setOnSvrEventListener(new MyOnSvrEventListener(svrVideoView));
			
			//Banner底部原点展示
			imageView = new ImageView(getActivity());
			LayoutParams params = new LayoutParams(DensityUtil.dip2px(getActivity(), 6), DensityUtil.dip2px(getActivity(), 6));
			params.setMargins(10, 0, 10, 0);
			imageView.setLayoutParams(params);
			
			imageViews[i] = imageView;
			if (i == 0) {
				imageViews[i]
						.setBackgroundResource(R.drawable.hot_point_s);
						
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.hot_point_n);
			}
			group.addView(imageViews[i]);
			
		}
		
		MyLog.d(TAG, "svrVideoViewList size : " + svrVideoViewList.size());
		
		advPager.setAdapter(new HotTrailerPagerAdapter(getActivity(),svrVideoViewList));
		advPager.setOnPageChangeListener(new GuidePageChangeListener(bannersDtos));
		advPager.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				MyLog.d(TAG, "event aciton : " + event.getAction());
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					stopVideoPlay();
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});
		
		if(myThread == null){
			myThread = new MyThread();
			myThread.start();
		}
		
		if(adapter != null){
			adapter.setHeaderView(banner_rootView);
		}
	}
	
	
	private class MyThread extends Thread{
		@Override
		public void run() {
			super.run();
			while (isWhileLoop) {
				Message msg = viewHandler.obtainMessage();
				if (isContinue) {
					msg.what = MSG_WHAT_BANNER_POINT;
					msg.arg1 = atomicInteger.get();
					viewHandler.sendMessage(msg);
					whatOption();
				} else {
					viewHandler.removeMessages(MSG_WHAT_BANNER_POINT);
				}
			}
		}
	}
	
	
	private void whatOption() {
		atomicInteger.incrementAndGet();
		if (atomicInteger.get() > imageViews.length - 1) {
			atomicInteger.getAndSet(0);
		}
		try {
			Thread.sleep(MSG_DELAY_BANNER_POINT);
		} catch (InterruptedException e) {
			
		}
	}

	public class MyOnSvrEventListener implements OnSvrEventListener {
		private SvrVideoView svrVideoView;
		
		public MyOnSvrEventListener(SvrVideoView svrVideoView){
			this.svrVideoView = svrVideoView;
		}

		@Override
		public void onControlViewClick() {
			toPlayVideo(svrVideoView);
		}

		@Override
		public void onPlayerEvent(playerEvent event) {
			switch (event) {
			case View_playing:
				MyLog.d(TAG, "View_playing--");
				break;
			case View_stop:
				MyLog.d(TAG, "View_stop--");
				videoNotPlayUI();
				break;
			case View_end:
				MyLog.d(TAG, "View_end--");
				svrVideoView.stopVideo();
				videoNotPlayUI();
				break;
			case View_showPoster:
				MyLog.d(TAG, "View_showPoster--");
				videoNotPlayUI();
				break;
			case View_showvideo:
				MyLog.d(TAG, "View_showvideo--");
				break;
			}
		}
		
	}
	
	public void toPlayVideo(final SvrVideoView svrVideoView) {
		// Wifi Mobile 网络提醒
		final int netWorkState = NetworkUtils.getNetConnectState(getActivity());
		if (netWorkState == NetworkUtils.STATE_CONNECT_WIFI) {
			toPlayVideoNow(svrVideoView);
		} else {
			String message = null;
			if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
				message = getActivity().getString(R.string.wifi_not_play_tip);
			} else if (netWorkState == NetworkUtils.STATE_CONNECT_NONE) {
				message = getActivity().getString(R.string.wifi_and_mobie_not_play_tip);
			}
			DialogUtils.showConfirmDialogConfirmCancel(getActivity(), null, message,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
								toPlayVideoNow(svrVideoView);

							}
							dialog.dismiss();
						}
					}, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
		}
	}
	
	public void toPlayVideoNow(final SvrVideoView svrVideoView) {
		if (svrVideoView.isShowingVideo()) {
			if (svrVideoView.isPlayingVideo()) {
				MyLog.d(TAG, "toPlayVideoNow pause video");
				svrVideoView.PauseVideo();
				videoPauseUI();
			} else {
				svrVideoView.ResumeVideo();
				MyLog.d(TAG, "toPlayVideoNow resume video");
				videoPlayingUI();
			}
		} else {
			svrVideoView.startVideo();
			MyLog.d(TAG, "toPlayVideoNow start video");
			videoPlayingUI();
		}
	}
	
	
	private SvrVideoView getCurSvrVideoView(){
		if(svrVideoViewList != null && (cursvrVideoViewPosition >= 0 && cursvrVideoViewPosition < svrVideoViewList.size())){
			return (SvrVideoView) svrVideoViewList.get(cursvrVideoViewPosition);
		}
		return null;
	}
	
	private void startVideoPlay(){
		SvrVideoView svrVideoView = getCurSvrVideoView();
		if(svrVideoView != null){
			svrVideoView.startVideo();
			videoPlayingUI();
		}
	}
	
	private void stopVideoPlay(){
		SvrVideoView svrVideoView = getCurSvrVideoView();
		if(svrVideoView != null && svrVideoView.isShowingVideo()){
			svrVideoView.stopVideo();
			videoNotPlayUI();
		}
	}
	
	private void stopVideoPlay(SvrVideoView svrVideoView){
		if(svrVideoView != null && svrVideoView.isShowingVideo()){
			svrVideoView.stopVideo();
			videoNotPlayUI();
		}
	}
	
	private void stopAllVideoPlay(){
		if(svrVideoViewList != null && svrVideoViewList.size() > 0){
			for(View view : svrVideoViewList){
				SvrVideoView svrVideoView = (SvrVideoView) view;
				stopVideoPlay(svrVideoView);
			}
		}
	}
	
//	private void pauseVideoPlay(){
//		SvrVideoView svrVideoView = getCurSvrVideoView();
//		if(svrVideoView != null && svrVideoView.isShowingVideo() && svrVideoView.isPlayingVideo()){
//			svrVideoView.PauseVideo();
//			videoPauseUI();
//		}
//	}
//	
//	private void resumeVideoPlay(){
//		SvrVideoView svrVideoView = getCurSvrVideoView();
//		if(svrVideoView != null && svrVideoView.isShowingVideo() && !svrVideoView.isPlayingVideo()){
//			svrVideoView.ResumeVideo();
//			videoPlayingUI();
//		}
//	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.banner_play_iv:
			if(cursvrVideoViewPosition >= 0 && svrVideoViewList != null){
				isContinue = false;
				if(cursvrVideoViewPosition >= svrVideoViewList.size()){
					cursvrVideoViewPosition = 0;
				}
				SvrVideoView svrVideoView = (SvrVideoView) svrVideoViewList.get(cursvrVideoViewPosition);
				if(svrVideoView.isShowingVideo()){
					//由于在全屏下暂停如果再回到小屏则视频掉播放结束回调，此处做stopVideo处理
					svrVideoView.stopVideo();
					videoNotPlayUI();
				}else{
					toPlayVideo(svrVideoView);
				}
			}
			break;
		}
	}
	
	private void videoNotPlayUI(){
		banner_cover_ui_relative.setVisibility(View.VISIBLE);
		banner_play_iv.setImageResource(R.drawable.banner_play_selector);
		isContinue = true;
	}
	
	
	private void videoPlayingUI() {
		banner_cover_ui_relative.setVisibility(View.INVISIBLE);
		banner_play_iv.setImageResource(R.drawable.banner_pause_selector);
		
	}
	
	private void videoPauseUI(){
		banner_cover_ui_relative.setVisibility(View.INVISIBLE);
		banner_play_iv.setImageResource(R.drawable.banner_play_selector);
	}
	
	
	private final class GuidePageChangeListener implements OnPageChangeListener {
		private List<BannersDto> bannersDtos;
		
		public GuidePageChangeListener(List<BannersDto> bannersDtos){
			this.bannersDtos = bannersDtos;
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(final int arg0) {
			//MyLog.d(TAG, "onPageSelected position : " + arg0);
			cursvrVideoViewPosition = arg0;
			BannersDto curBannerDto = bannersDtos.get(arg0);
			banner_title_tv.setText(curBannerDto.getTitle());
			banner_remark_tv.setText(curBannerDto.getRemark());
			for (int i = 0; i < imageViews.length; i++) {
				imageViews[arg0]
						.setBackgroundResource(R.drawable.hot_point_s);
				if (arg0 != i) {
					imageViews[i]
							.setBackgroundResource(R.drawable.hot_point_n);
				}
			}

		}

	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMessageEvent(EventBusBean event){
		String eventMessage = event.getMessage();
		MyLog.d(TAG, "onMessageEvent : " + eventMessage);
		if(eventMessage.equals(EventBusUtils.EVENT_VIDEODETAILDIALOG_CREATE)){
			//isContinue = false;
			stopVideoPlay();
		}else if(eventMessage.equals(EventBusUtils.EVENT_VIDEODETAILDIALOG_DISMISS)){
			//isContinue = true;
		}
	}
	
	private List<GameItem> getGameListRefresh(){
		return getGameListRefresh(false);
	}
	
	/**
	 * 获取视频列表
	 * 以SQLite形式缓存网络Json
	 */
	private List<GameItem> getGameListRefresh(boolean update){
		getBannerList(update);
		MyLog.d(TAG, "getGameListRefresh...update : " + update);
		List<GameItem> list = dataCenter.getGameListSort(true, update,true);
		if (list != null){
			MyLog.d(TAG, "getGameListRefresh list size : " + list.size());
			if(list.size() > 0){
				if(gameList == null)gameList = new ArrayList<GameItem>();
				if (adapter != null) {
					MyLog.d(TAG, "adapter != null");
					adapter.addList(list, false);
				} else {
					gameList.addAll(list);
				}
			}
		}
		return list;		
	}
	
	private List<GameItem> getGameListMore() {
		MyLog.d(TAG, "getGameListMore...");
		List<GameItem> list = dataCenter.getGameListSort(true, false,false);
		if (list != null){
			MyLog.d(TAG, "getGameListMore list size : " + list.size());
			if (list.size() > 0) {
				if(gameList == null)gameList = new ArrayList<GameItem>();
				if (adapter != null) {
					MyLog.d(TAG, "adapter != null");
					adapter.addList(list, false);
				} else {
					gameList.addAll(list);
				}
			}
		}
		return list;
	}
	
	@Override
	public void onLoadMore() {
		swipeToLoadLayout.post(new Runnable() {
			@Override
			public void run() {
				//上拉加载
				MyLog.d(TAG, "load more...");
				getGameListMore();
				swipeToLoadLayout.setLoadingMore(false);
				
			}
		});
	}

	@Override
	public void onRefresh() {
		swipeToLoadLayout.post(new Runnable() {
			@Override
			public void run() {
				//下拉刷新
				MyLog.d(TAG, "refreshing...");
				getGameListRefresh(true);
				swipeToLoadLayout.setRefreshing(false);
			}
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		isContinue = true;
		
		EventBus.getDefault().register(this);
		
		if(adapter != null){
			
			adapter.onResume();
			
		}
		
		MyLog.d(TAG, "isHomeIn : " + isHomeIn + " isScreenOn : " + isScreenOn);
		
		//Home或者电源键返回后加载数据
		if(isHomeIn || isScreenOn){
			
			isHomeIn = false;
			isScreenOn = false;
			
			getGameListRefresh(true);
			
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		
		isContinue = false;
		
		stopVideoPlay();
		
		EventBus.getDefault().unregister(this);
		
		if(adapter != null){
			
			adapter.onPause();
			
		}
	}
	
	@Override
	public void onStop() {
		super.onStop();
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		dataCenter.delGameEventListener(KEY);
		dataCenter.delBannerEventListener(KEY);
	}
	
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		  if (mScreenObserver != null) {
	            mScreenObserver.stopScreenStateUpdate();
	        }
		  
		  if(mHomeListen != null) mHomeListen.stop();
	}
}
